<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="基础信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="8">
                <px-form-item label="工具编码" prop="toolCode">
                  <px-input v-model="formValue.toolCode" placeholder="请输入工具编码" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工具分类" prop="toolCategory">
                  <px-select v-model="formValue.toolCategory" placeholder="请选择工具分类" filterable clearable>
                    <px-option v-for="item in toolCategoryList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工具名称" prop="toolName">
                  <px-input v-model="formValue.toolName" placeholder="请输入工具名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工具单位" prop="toolUnit">
                  <px-select v-model="formValue.toolUnit" placeholder="请选择工具单位" filterable clearable>
                    <px-option v-for="item in toolUnitList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <!-- <px-select v-model="formValue.className" placeholder="请选择工具科室" filterable clearable>
                    <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select> -->
                <EquipClassSelect customLabel="工具科室" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="资产标签" prop="assetTag">
                  <px-select v-model="formValue.assetTag" placeholder="请选择单位" filterable clearable>
                    <px-option v-for="item in assetTagList" :key="item.value" :label="item.label" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="管理人" prop="custodianBy">
                  <px-select-v2
                    v-model="formValue.custodianBy"
                    filterable
                    clearable
                    :options="custodianList"
                    placeholder="请选择管理人"
                    @change="custodianChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="生产日期" prop="productionDate">
                  <px-date-picker v-model="formValue.productionDate" :disabled-date="disabledDate" value-format="YYYY-MM-DD" />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.toolCategory !== 'key tools'" :span="8">
                <px-form-item label="型号/规格" prop="toolModel">
                  <px-input v-model="formValue.toolModel" placeholder="请输入型号/规格" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.toolCategory !== 'key tools'" :span="8">
                <px-form-item label="品牌" prop="brandVal">
                  <px-input v-model="formValue.brandVal" placeholder="请输入品牌" maxlength="50" clearable />
                  <!-- <px-select v-model="formValue.brandVal" placeholder="请选择品牌" clearable>
                    <px-option v-for="item in brandValList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select> -->
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工具位置" prop="toolPosition">
                  <px-input v-model="formValue.toolPosition" placeholder="请输入工具位置" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="下次校验日期" prop="checkDate">
                  <px-date-picker v-model="formValue.checkDate" :disabled-date="disabledRemindDate" value-format="YYYY-MM-DD" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="提醒时间" prop="noticeTime">
                  <px-select v-model="formValue.noticeTime" placeholder="请选择校验提醒时间" filterable clearable>
                    <px-option v-for="item in noticeTimeList" :key="item.value" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="厂区" prop="factoryAreaCode">
                  <px-select v-model="formValue.factoryAreaCode" disabled placeholder="请选择厂区" style="width: 100%">
                    <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    placeholder="请输入备注信息"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="工具图片">
        <template v-slot:content>
          <PhotoUpload
            v-if="!isMain && !isView"
            photoType="add"
            :photoData="{ moduleName: moduleName }"
            :photoList="formValue.toolPic"
            style="margin-bottom: 18px"
            @changePhotoList="changePhotoList"
            @savePhotoStatus="savePhotoStatus"
          />
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="检测报告">
        <template v-slot:content>
          <FileUpload
            fileType="edit"
            :fileData="{ moduleName: moduleName }"
            :fileList="formValue.checkReportList"
            style="margin-bottom: 18px"
            @changeFileList="changeFileList"
            @saveFileStatus="saveFileStatus"
          />
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
// import { addToolLedger, getModuleName, getToolInfoCode } from "@/api/equip/toolManage";
import { addToolLedger, editToolLedger, getModuleName, getTimeList, getToolLedger } from "@/api/equip/toolManage";
import FileUpload from "@/components/Upload/FileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import { assetTagList } from "../../data";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);

// 父级传过来的值
const props = defineProps({
  // 主页面/详情页面
  isMain: {
    type: Boolean,
    default: false
  },
  // 查看or新增/编辑
  isView: {
    type: Boolean,
    default: false
  },
  toolId: {}
});

// 获取系统中的统一的厂区，下拉框处理
const facCode = ref(localStorage.getItem("facCode"));
const facList = JSON.parse(localStorage.getItem("facList"));

// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    toolPic: [],
    factoryAreaCode: facCode
  },
  // brandValList: [], // 品牌下拉框
  // classNameList: [], // 工具科室下拉框
  toolCategoryList: [], // 工具分类下拉框
  toolUnitList: [], // 单位下拉框
  custodianList: [], // 责任人下拉框
  noticeTimeList: [], // 提醒时间列表
  imageVisible: false,
  moduleName: "",
  photoStatusFlag: false,
  fileStatusFlag: false
});
const { formValue, toolUnitList, custodianList, noticeTimeList, toolCategoryList, moduleName, photoStatusFlag, fileStatusFlag } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  toolCode: [{ required: true, message: "工具编码不能为空", trigger: "blur" }],
  factoryAreaCode: [{ required: true, message: "厂区不能为空", trigger: "blur" }],
  toolCategory: [{ required: true, message: "工具分类不能为空", trigger: "change" }],
  toolName: [{ required: true, message: "工具名称不能为空", trigger: "blur" }],
  toolUnit: [{ required: true, message: "工具单位不能为空", trigger: "change" }],
  toolModel: [{ required: true, message: "型号/规格不能为空", trigger: "change" }],
  brandVal: [{ required: true, message: "品牌不能为空", trigger: "change" }],
  className: [{ required: true, message: "工具科室不能为空", trigger: "change" }],
  assetTag: [{ required: true, message: "资产标签不能为空", trigger: "change" }],
  custodianBy: [{ required: true, message: "管理人不能为空", trigger: "change" }],
  checkDate: [{ required: formValue.value.noticeTime, message: "下次校验日期不能为空", trigger: "blur" }],
  noticeTime: [{ required: formValue.value.checkDate, message: "提醒时间不能为空", trigger: "blur" }]
}));

// 科室组件调用父组件
const changeClassName = val => {
  formValue.value.className = val;
};

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};

const disabledRemindDate = (time: Date) => {
  return time.getTime() < Date.now() - 86400000; // 禁用今天之前的日期
};

// 监视isMain和isView值
watch(isMain, async val => {
  formRef.value.resetFields();
  if (!val && !props.isView) {
    formValue.value = {
      toolPic: [],
      checkReportList: [],
      factoryAreaCode: facCode
    };
    queryDictValSelect();
    // getToolCode();
    getModuleNameValue();
    custodianList.value = await getEmployeeIdAndName();
    formRef.value.clearValidate();
    if (props.toolId) {
      const res = await getToolLedger({ id: props.toolId });
      const { noticeTime } = res;
      formValue.value = { ...res, noticeTime: noticeTime === "0" ? "" : noticeTime };
    }
  }
});

// 获取后端自动生成的工具编码
// const getToolCode = async () => {
//   const data = await getToolInfoCode();
//   formValue.value.toolCode = data;
// };
// 字典
const queryDictValSelect = async () => {
  // brandValList.value = await queryDictData({ typeCode: "toolBrand" }); // 品牌下拉框
  // classNameList.value = await queryCurrentClassList(); // 工具科室下拉框
  toolUnitList.value = await queryDictData({ typeCode: "unit" }); // 单位下拉框
  toolCategoryList.value = await queryDictData({ typeCode: "toolCategory" }); // 工具分类下拉框
  noticeTimeList.value = await getTimeList();
};

// 获取principalName
const custodianChange = val => {
  const arr = custodianList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.custodianName = arr[0].label;
  }
};

// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getModuleName({});
  moduleName.value = data;
};

// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};

// 新的图片列表
const changePhotoList = val => {
  formValue.value.toolPic = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

// 新的文件列表
const changeFileList = val => {
  formValue.value.checkReportList = val;
};

// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const picList = [];
      if (formValue.value.toolPic && formValue.value.toolPic.length > 0) {
        formValue.value.toolPic.forEach(item => {
          if (item?.id) {
            picList.push(item.id);
          } else if (item?.response.data.id) {
            picList.push(item.response.data.id);
          }
        });
      }
      const fileList = [];
      if (formValue.value.checkReportList && formValue.value.checkReportList.length > 0) {
        formValue.value.checkReportList.forEach(item => {
          if (item?.id) {
            fileList.push(item.id);
          } else if (item?.response.data.id) {
            fileList.push(item.response.data.id);
          }
        });
      }
      if (props.toolId) {
        // TODO 编辑
        await editToolLedger({ ...formValue.value, checkReportList: fileList, toolPic: picList });
        PxMessage.success("修改成功!");
        backMainPage();
        emits("queryTable");
      } else {
        await addToolLedger({ ...formValue.value, checkReportList: fileList, toolPic: picList });
        PxMessage.success("创建成功!");
        backMainPage();
        emits("queryTable");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
